package com.cpd.blog.common.utils;

import com.cpd.blog.common.constant.RedisKey;
import com.cpd.blog.common.constant.StatusCode;
import com.cpd.blog.dto.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Copydown
 * @date 2022/08/13/21:36
 */
@Component
@RequiredArgsConstructor
public class EmailUtil {

    private final RedisUtil redisUtil;

    private final JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public Result sendEmailSmsCode(Boolean isSend) {

        String codeKey = RedisKey.EMAIL_PWD_CODE + CurrentUser.getId();

        if (CheckUtil.isNotNull(redisUtil.get(codeKey))) {
            return Result.fail(StatusCode.VERIFY_CODE_FREQUENT);
        }

        String email = CurrentUser.getEmail();
        String code = GenerateUtil.genUuidSize6();

        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(email);
            message.setSubject("时光序邮箱验证");
            message.setText("您的验证码为：" + code + "\n(有效期5分钟)");
            if (CheckUtil.isTrue(isSend)) {
                mailSender.send(message);
            } else {
                System.out.println(code);
            }
            redisUtil.set(codeKey, code, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            return Result.fail(StatusCode.EMAIL_SEND_FAILED);
        }

        return Result.success();
    }
}
